﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace AudioBook.AudioManagement.FileManage
{
    public partial class EditFolder : System.Web.UI.Page
    {
        #region Private methods

        private bool SaveFileFolder()
        {
            string currentFolder = GlobalParam.RootFileFolder + hidCurrentFolder.Value;
            string parentFolder = GlobalParam.RootFileFolder + hidParentFolder.Value + "\\";

            if (Directory.Exists(currentFolder))
            {
                string newName = parentFolder + txtNewName.Text;
                if (string.IsNullOrEmpty(txtNewName.Text.Trim()) || Directory.Exists(newName))
                {
                    valCommon.ErrorMessage = "Folder's name invalid or existed";
                    valCommon.IsValid = false;
                    return false;
                }
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(currentFolder);
                    dir.MoveTo(newName);
                }
                catch (Exception ex)
                {
                    valCommon.ErrorMessage = ex.Message;
                    valCommon.IsValid = false;
                    return false;
                }
            }

            return true;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString[GUIConstants.Common.ID_QUERY] != null && Request.QueryString[GUIConstants.Common.ID_QUERY] != string.Empty)
            {
                hidCurrentFolder.Value = Request.QueryString[GUIConstants.Common.ID_QUERY];
                txtCurrentFile.Text = hidCurrentFolder.Value;
                string currentFolder = hidCurrentFolder.Value;
                currentFolder = currentFolder.Substring(0, currentFolder.Length - 1);
                hidParentFolder.Value = currentFolder.Substring(0, currentFolder.LastIndexOf("\\") + 1);
            }
        }

        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            bool result = SaveFileFolder();
            if (result)
            {
                Response.Redirect(GUIConstants.WebPage.FilePage.DefaultFile + "?id=" + hidParentFolder.Value);
            }
        }

        protected void btnSaveAndNew_Click(object sender, EventArgs e)
        {
            bool result = SaveFileFolder();
            if (result)
            {
                Response.Redirect(Request.Url.ToString());
            }
        }
    }
}
